#Copyright (C) Nial Peters 2012
#
#This file is part of AvoScan.
#
#AvoScan is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#AvoScan is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with AvoScan.  If not, see <http://www.gnu.org/licenses/>.
"""
This module deals with handling templates for field notes. Templates 
provide a simple way to ensure that all relevant information gets 
recorded by the operator. They also allow "constant" information 
about the field site (such as GPS coordinates) to always be recorded
but without the operator having to input them.
"""
import os.path

import avoscan

class TemplateManager:
    """
    Class for managing field notes template files.
    """
    def __init__(self):
        self.template_dir = os.path.join(avoscan.get_avoscan_rw_dir(),'templates')

    
    def get_template_names(self):
        """
        Returns a list of available template names (basically the filenames
        in the templates folder) sorted in alphabetical order.
        """
        return sorted(os.listdir(self.template_dir))
    
    
    def create_new_template(self, name, contents="", force=False):
        """
        Creates a new template called 'name' containing 'contents'.
        Raises ValueError if there is already a template called 'name'
        unless force=True, in which case it will be overwritten.
        """
        
        if not force and name in self.get_template_names():
            raise ValueError("A template named %s already exists."%name)
        
        #create the template file
        with open(os.path.join(self.template_dir, name), 'w') as ofp:
            ofp.write(contents)
    
    
    def load_template(self, template_name):
        """
        Returns the contents of the specified template file as a string.
        If the template_name is equal to the string "None" then an empty
        string is returned.
        """
        if template_name == "None":
            return ""
            
        path_to_template = os.path.join(self.template_dir, template_name)
        
        with open(path_to_template, "r") as ifp:
            template = ifp.read()
        
        return template
    
    
    def delete_template(self, template_name):
        """
        Removes the specified template from the filesystem. This cannot be undone!
        """
        path_to_template = os.path.join(self.template_dir, template_name)
        os.remove(path_to_template)